import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Progress } from "./ui/progress";
import { Badge } from "./ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { HardDrive, TrendingUp, Database, Archive } from "lucide-react";
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, BarChart, Bar } from "recharts";
import { useI18n } from "../lib/i18n/context";
import { useDataSource } from "../lib/data/context";

const mockStorageData = [
  { name: 'Jan', used: 120, total: 500 },
  { name: 'Feb', used: 135, total: 500 },
  { name: 'Mar', used: 148, total: 500 },
  { name: 'Apr', used: 162, total: 500 },
  { name: 'May', used: 178, total: 500 },
  { name: 'Jun', used: 195, total: 500 },
  { name: 'Jul', used: 214, total: 500 },
  { name: 'Aug', used: 235, total: 500 },
  { name: 'Sep', used: 258, total: 500 },
  { name: 'Oct', used: 283, total: 500 },
  { name: 'Nov', used: 310, total: 500 },
  { name: 'Dec', used: 340, total: 500 }
];

const mockDatabaseSizes = [
  { name: 'users', size: 85, color: '#8884d8' },
  { name: 'orders', size: 120, color: '#82ca9d' },
  { name: 'products', size: 45, color: '#ffc658' },
  { name: 'analytics', size: 60, color: '#ff7300' },
  { name: 'logs', size: 30, color: '#00ff00' }
];

const mockTableSizes = [
  { name: 'order_items', size: 45.2, growth: 12.5 },
  { name: 'user_sessions', size: 38.7, growth: 8.3 },
  { name: 'product_reviews', size: 22.1, growth: 15.2 },
  { name: 'analytics_events', size: 18.9, growth: 22.1 },
  { name: 'transaction_logs', size: 14.3, growth: 5.7 },
  { name: 'user_preferences', size: 12.8, growth: 3.2 },
  { name: 'email_queue', size: 8.5, growth: -2.1 },
  { name: 'cache_entries', size: 6.2, growth: 1.8 }
];

export function DatabaseSpaceMonitor() {
  const { t } = useI18n();
  const { databases } = useDataSource();
  const [selectedInstance, setSelectedInstance] = useState<string>('');

  const selectedDb = databases.find(db => db.id === selectedInstance);
  const totalUsed = selectedDb ? selectedDb.storage : 340;
  const totalCapacity = selectedDb ? selectedDb.storage * 1.5 : 500;
  const usagePercentage = (totalUsed / totalCapacity) * 100;

  const getUsageColor = (percentage: number) => {
    if (percentage >= 90) return 'text-red-600';
    if (percentage >= 75) return 'text-orange-600';
    if (percentage >= 50) return 'text-yellow-600';
    return 'text-green-600';
  };

  const getUsageBadgeColor = (percentage: number) => {
    if (percentage >= 90) return 'destructive';
    if (percentage >= 75) return 'secondary';
    return 'default';
  };

  return (
    <div className="space-y-6">
      {/* Instance Selector */}
      <Card>
        <CardHeader>
          <CardTitle>{t.storage.title}</CardTitle>
        </CardHeader>
        <CardContent>
          <Select value={selectedInstance} onValueChange={setSelectedInstance}>
            <SelectTrigger className="w-full sm:w-[300px]">
              <SelectValue placeholder={t.slowQueries.chooseDatabase} />
            </SelectTrigger>
            <SelectContent>
              {databases.map(db => (
                <SelectItem key={db.id} value={db.id}>
                  {db.name} ({db.status})
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </CardContent>
      </Card>

      {!selectedInstance ? (
        <Card className="text-center py-12">
          <CardContent>
            <Database className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
            <h3 className="text-lg font-medium mb-2">{t.performance.selectInstance}</h3>
            <p className="text-muted-foreground">
              Choose a database instance from the dropdown above to view its storage usage
            </p>
          </CardContent>
        </Card>
      ) : (
        <>
          {/* Overview Cards */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="flex items-center p-6">
            <div className="flex items-center space-x-4">
              <HardDrive className="h-8 w-8 text-blue-600" />
              <div>
                <p className="text-sm text-muted-foreground">{t.storage.totalStorage}</p>
                <p className="text-2xl font-bold">{totalCapacity} GB</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="flex items-center p-6">
            <div className="flex items-center space-x-4">
              <Database className="h-8 w-8 text-green-600" />
              <div>
                <p className="text-sm text-muted-foreground">{t.storage.usedStorage}</p>
                <p className={`text-2xl font-bold ${getUsageColor(usagePercentage)}`}>
                  {totalUsed} GB
                </p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="flex items-center p-6">
            <div className="flex items-center space-x-4">
              <Archive className="h-8 w-8 text-purple-600" />
              <div>
                <p className="text-sm text-muted-foreground">{t.storage.available}</p>
                <p className="text-2xl font-bold">{totalCapacity - totalUsed} GB</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="flex items-center p-6">
            <div className="flex items-center space-x-4">
              <TrendingUp className="h-8 w-8 text-orange-600" />
              <div>
                <p className="text-sm text-muted-foreground">{t.storage.usagePercent}</p>
                <div className="flex items-center space-x-2">
                  <p className={`text-2xl font-bold ${getUsageColor(usagePercentage)}`}>
                    {usagePercentage.toFixed(1)}%
                  </p>
                  <Badge variant={getUsageBadgeColor(usagePercentage)}>
                    {usagePercentage >= 75 ? t.storage.high : t.storage.normal}
                  </Badge>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Storage Usage Progress */}
      <Card>
        <CardHeader>
          <CardTitle>{t.storage.usageOverview}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div className="flex justify-between items-center">
              <span>{t.storage.currentUsage}</span>
              <span className={getUsageColor(usagePercentage)}>
                {totalUsed} GB of {totalCapacity} GB ({usagePercentage.toFixed(1)}%)
              </span>
            </div>
            <Progress value={usagePercentage} className="h-3" />
            {usagePercentage >= 75 && (
              <div className="flex items-center space-x-2 text-orange-600 text-sm">
                <TrendingUp className="h-4 w-4" />
                <span>
                  {usagePercentage >= 90 ? t.storage.criticallyHigh : t.storage.significantlyHigh}
                </span>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Charts Row */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Storage Growth Trend */}
        <Card>
          <CardHeader>
            <CardTitle>{t.storage.growthTrend}</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={mockStorageData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="name" />
                <YAxis />
                <Tooltip 
                  formatter={(value, name) => [
                    `${value} GB`, 
                    name === 'used' ? t.storage.usedStorage : t.storage.totalCapacity
                  ]}
                />
                <Line 
                  type="monotone" 
                  dataKey="used" 
                  stroke="#8884d8" 
                  strokeWidth={2}
                  dot={{ fill: '#8884d8' }}
                />
                <Line 
                  type="monotone" 
                  dataKey="total" 
                  stroke="#82ca9d" 
                  strokeDasharray="5 5"
                />
              </LineChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Database Size Distribution */}
        <Card>
          <CardHeader>
            <CardTitle>{t.storage.sizeDistribution}</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={mockDatabaseSizes}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={({ name, value }) => `${name}: ${value}GB`}
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="size"
                >
                  {mockDatabaseSizes.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip formatter={(value) => [`${value} GB`, t.storage.size]} />
              </PieChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>

      {/* Largest Tables */}
      <Card>
        <CardHeader>
          <CardTitle>{t.storage.largestTables}</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {mockTableSizes.map((table, index) => (
              <div key={table.name} className="flex items-center justify-between p-3 border rounded-lg">
                <div className="flex items-center space-x-3">
                  <div className="w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center text-xs">
                    {index + 1}
                  </div>
                  <div>
                    <p className="font-medium">{table.name}</p>
                    <p className="text-sm text-muted-foreground">{table.size} GB</p>
                  </div>
                </div>
                <div className="flex items-center space-x-2">
                  <Badge 
                    variant={table.growth > 10 ? 'destructive' : table.growth > 0 ? 'secondary' : 'default'}
                  >
                    {table.growth > 0 ? '+' : ''}{table.growth}%
                  </Badge>
                  <Progress value={(table.size / 50) * 100} className="w-20 h-2" />
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
        </>
      )}
    </div>
  );
}